package com.youngking.guns.modular.weixin;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.weixin4j.WeixinException;
import org.weixin4j.model.message.OutputMessage;
import org.weixin4j.model.message.event.*;

import org.weixin4j.spi.IEventMessageHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号认证登录
 * 开发平台认证登录类似
 */
@Controller
@PropertySource("classpath:/weixin4j.properties")
@RequestMapping("/loginwxController")
    public class LoginwxController{
        @Value("${weixin4j.oauth.appid}")
        private String appid;  //验证码发送key
        @Value("${weixin4j.oauth.secret}")
        private String appsecret;  //验证码秘钥
        /**
         * https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
         * 若提示“该链接无法访问”，请检查参数是否填写错误，是否拥有scope参数对应的授权作用域权限。
         */
    @RequestMapping("/doGet")
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String type = request.getParameter("itype");
        String backUrl = "http://www.ynyxgcxx.com/projectmanage/callBackController/callBack";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + appid +
                "&redirect_uri=" + URLEncoder.encode(backUrl) +
                "&response_type=code" +
                //"&scope=snsapi_userinfo" +
                "&scope=snsapi_base" +
                "&state="+type+"#wechat_redirect";
        response.sendRedirect(url);
    }

    /**
     * 微信消息接收和token验证
     * @param model
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/ownerCheck")
    public void ownerCheck(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException, WeixinException {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        Map map=xmlToMap(request);
        System.out.println(map);
        PrintWriter print;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            /* if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {*/
            try {
                print = response.getWriter();
                print.write(echostr);
                print.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*  }*/
        }

    }
    public static Map<String,String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        //用List列表的方式来解析xml,详细见http://www.jb51.net/article/42323.htm
        Map<String, String> map =new HashMap<String,String>();  //把客户端传过来的xml数据转换成map格式的数据

        SAXReader reader =new SAXReader();


        InputStream ins=request.getInputStream();//从request中获取输入流
        Document doc =reader.read(ins);// 弄成文本？？？Xml

        Element root =doc.getRootElement();
        List<Element> list =root.elements();//获取子节点元素
        //list相当于一个变量，List则是标明是何种变量，这样来理解
        for(Element e :list){
            map.put(e.getName(), e.getText());	                 //将遍历的结果保存到集合中
        }
        ins.close();
        return map;

    }
}